/**
 * All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
 * MeetRoomManageController
 * 会议室管理
 * 修改纪录
 * 2020-10-26 版本：1.0 wanghongwei 创建。
 *
 * @version 版本：1.0
 * @author 作者：wanghongwei
 * 创建日期：2020-10-26
 */
package com.topscomm.meet.controller;

import java.util.*;

import javax.annotation.Resource;

import com.topscomm.cbo.pojo.CboRoleEntity;
import com.topscomm.meet.MeetSystemConst;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.topscomm.base.service.impl.BaseShareManageService;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.meet.MeetSystemConst.MeetRoomTypeEnum;
import com.topscomm.meet.controller.auto.MeetRoomManageControllerAuto;
import com.topscomm.meet.service.IMeetManageService;
import com.topscomm.meet.service.IMeetRoomApplyService;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.DateUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.vo.ResponseResult;

/**
 * @author: wanghongwei
 * @date: 2020-10-26
 * @description:会议室管理Controller
 * @modify:
 */
@RestController
@RequestMapping("meet/roomManage")
public class MeetRoomManageController extends MeetRoomManageControllerAuto implements IMeetRoomManageController {
	/**
	 * 会议室预约记录
	 */
	@Resource(name = "meetRoomApplyService")
	private IMeetRoomApplyService meetRoomApplyService;
	/**
	 * 会议室记录
	 */
	@Resource(name = "meetManageService")
	private IMeetManageService meetManageService;

	/**
	 * @author: wanghongwei
	 * @date: 2020-10-26
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	protected String spellListSql(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" 1=1 ");
		if (paraMap.containsKey("qry_name")) {
			String value = paraMap.get("qry_name").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and name like '%{0}%' ", value);
		}
		if (paraMap.containsKey("qry_location")) {
			String value = paraMap.get("qry_location").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and location = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_capacity")) {
			String value = paraMap.get("qry_capacity").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and capacity >= {0}", value);
		}
		if (paraMap.containsKey("qry_type")) {
			String value = paraMap.get("qry_type").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and type = '{0}'", value);
		}
		if (paraMap.containsKey("qry_locationdesc")) {
			String value = paraMap.get("qry_locationdesc").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and locationdesc like '%{0}%'", value);
		}
		if (paraMap.containsKey("qry_availabledeptcode")) {
			String value = paraMap.get("qry_availabledeptcode").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and ({0}) ",
						BaseShareManageService.createWhereDeptCheckInclude("availabledeptcode", value, ","));
		}
		// 权限控制
		String value = ConvertUtil.convertToString(paraMap.get("qry_type"));
		if (Objects.equals(value, MeetRoomTypeEnum.Dept) && this.getUserBean().getUser().getAdminlevel() < 9) {
			// 只能查看自己维护的会议室或自己部门的会议室
			String deptCode = this.getUserBean().getDept().getCode();
			String userCode = this.getUserBean().getUser().getCode();
			long userId = this.getUserBean().getUser().getId();
			sql.appendSingle(" and ({0} or usercode = '{1}' or createuser = {2})",
					BaseShareManageService.createWhereDeptCheckInclude("availabledeptcode", deptCode, ","), userCode,
					userId);
		}
		// 查询可见部门的会议室
		if (paraMap.containsKey("qry_available")) {
			String qry_available = paraMap.get("qry_available").toString();
			if (qry_available.equals("1")) {
				String deptsql = BaseShareManageService.createWhereDeptCheckInclude("availabledeptcode",
						this.getUserBean().getDept().getCode(), ",");
				sql.appendSingle(" and enabled=1 and ((type='{0}' and {1})  or (type in ('{2}','{3}')))", MeetRoomTypeEnum.Dept,
						deptsql, MeetRoomTypeEnum.Company,MeetRoomTypeEnum.Remote);
			}
		}
		return sql.toString();
	}

	/**
	 * @author: wanghongwei
	 * @date: 2020-10-26
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	@GetMapping(value = "/refList")
	public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
		return super.refList(paraMap);
	}

	/**
	 * @description:
	 * @return
	 * @author: donghang
	 * @date: 2020年11月9日上午12:31:56
	 * @modify:
	 */
	@GetMapping(value = "/queryAllMeetRoom")
	public ResponseResult<Object> queryAllMeetRoom(@RequestParam(required = false) Map<String, Object> paraMap) {
		// 1.查询权限内的会议室
		String meetRoomType = ConvertUtil.convertToString(paraMap.get("qry_meetroomtype"));
		StringBufferProxy sql = new StringBufferProxy();
		if (meetRoomType.equals(MeetRoomTypeEnum.Company)||meetRoomType.equals(MeetRoomTypeEnum.Remote)) {// 查询公司会议室
			sql.appendSingle("enabled=1 and type='{0}' order by sortcode", meetRoomType);
		} else {// 部门会议室要通过权限控制
			String deptsql = BaseShareManageService.createWhereDeptCheckInclude("availabledeptcode",
					this.getUserBean().getDept().getCode(), ",");
			sql.appendSingle("enabled=1 and ((type='{0}' and {1})  or (type='{2}') or (type='{3}') ) order by type asc,sortcode asc",
					MeetRoomTypeEnum.Dept, deptsql, MeetRoomTypeEnum.Company,MeetRoomTypeEnum.Remote);
		}
		List<Map<String, Object>> queryRoomList = this.service.queryMapByWhere(sql.toString());
		this.service.setDispFields(queryRoomList);
		return ResponseResult.ok(queryRoomList);
	}

	/**
	 * 查询会议室预约记录，图形展示使用
	 *
	 * @description:
	 * @param paraMap
	 * @return
	 * @author: donghang
	 * @date: 2020年11月9日上午8:19:50
	 * @modify:
	 */
	@GetMapping(value = "/queryApplyRecord")
	public ResponseResult<Object> queryApplyRecord(@RequestParam(required = false) Map<String, Object> paraMap) {
		List<Map<String, Object>> applyList = new ArrayList<>();
		// 公司会议室预约记录
		List<Map<String, Object>> colorList = datacodeCache.getCodeListMap("MeetRoomColor");
		String meetRoomType = ConvertUtil.convertToString(paraMap.get("qry_meetroomtype"));
		if (meetRoomType.equals(MeetRoomTypeEnum.Company)||meetRoomType.equals(MeetRoomTypeEnum.Remote)) {// 查询公司会议室
			applyList.addAll(this.meetRoomApplyService.queryRecentlyIndependApplyList(paraMap));
		} else {
			applyList.addAll(this.meetRoomApplyService.queryRecentlyIndependApplyList(paraMap));
			// 部门会议室
			List<Map<String, Object>> deptRoomList = this.meetManageService.queryMeetRoomRecentlyApplyList(paraMap);
			for (Map<String, Object> map : deptRoomList) {
				if (ConvertUtil.convertToInt(map.get("state")) == 1) {
					map.put("state", "9");
				}
			}
			applyList.addAll(deptRoomList);
		}
		for (Map<String, Object> map : applyList) {
			Map<String, Object> dispcolor = colorList.stream()
					.filter(item -> item.get("code").toString().equals(ConvertUtil.convertToString(map.get("state"))))
					.findFirst().orElse(null);
			String color = dispcolor == null ? "" : ConvertUtil.convertToString(dispcolor.get("name"));
			map.put("dispmarkcolor", color);
		}
		return ResponseResult.ok(applyList);
	}

	/**
	 * 查询会议室，携带预约记录
	 *
	 * @description:
	 * @param paraMap
	 *            qry_meetroomtype: company-查询公司级会议室，dept-查询公司级会议室，不写查询所有的会议室
	 * @return
	 * @author: donghang
	 * @date: 2020年10月27日下午1:53:46
	 * @modify:
	 */
	@GetMapping(value = "/queryMeetRoomWithAvailableList")
	public ResponseResult<Object> queryMeetRoomWithAvailableList(
			@RequestParam(required = false) Map<String, Object> paraMap) {
		List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
		// 1.查询权限内的会议室
		String meetRoomType = ConvertUtil.convertToString(paraMap.get("qry_meetroomtype"));
		StringBufferProxy sql = new StringBufferProxy();
		if (meetRoomType.equals(MeetRoomTypeEnum.Company) || meetRoomType.equals(MeetRoomTypeEnum.Remote) ) {// 查询公司会议室
			sql.appendSingle("enabled=1 and type='{0}' order by sortcode", meetRoomType);
		}else {// 部门会议室要通过权限控制
			String deptsql = BaseShareManageService.createWhereDeptCheckInclude("availabledeptcode",
					this.getUserBean().getDept().getCode(), ",");
			sql.appendSingle("enabled=1 and ((type='{0}' and {1})  or (type='{2}')) order by type asc,sortcode asc",
					MeetRoomTypeEnum.Dept, deptsql, MeetRoomTypeEnum.Company);
		}
		List<Map<String, Object>> queryRoomList = this.service.queryMapByWhere(sql.toString());
		this.service.setDispFields(queryRoomList);
		StringBuilder availableMeetRoomIds = new StringBuilder();
		for (Map<String, Object> boardroom : queryRoomList) {
			String showname = datacodeCache.getValueDynamic("MeetRoomType",ConvertUtil.convertToString(boardroom.get("type")),"code","name");
				boardroom.put("showname", "("+showname+ ")"+ ConvertUtil.convertToString(boardroom.get("name")));
			availableMeetRoomIds.append(ConvertUtil.convertToString(boardroom.get("id"))).append(",");
		}
		// 查询该会议室是否上传了图片
		this.service.addAttachmentState(queryRoomList);
		if (availableMeetRoomIds.length() > 0) {
			availableMeetRoomIds = new StringBuilder(availableMeetRoomIds.substring(0, availableMeetRoomIds.length() - 1));
			List<Map<String, Object>> applyList = new ArrayList<>();
			paraMap.put("qry_availmeetids", availableMeetRoomIds.toString());
			// 公司会议室预约记录
			paraMap.put("qry_begintime", DateUtil.dateToString(DateUtil.getNowDate()));
			applyList.addAll(this.meetRoomApplyService.queryRecentlyIndependApplyList(paraMap));
			// 部门级会议室预约记录
			applyList.addAll(this.meetManageService.queryMeetRoomRecentlyApplyList(paraMap));
			for (Map<String, Object> boardroom : queryRoomList) {
				for (Map<String, Object> applyEntity : applyList) {
					String meetRoomId = ConvertUtil.convertToString(applyEntity.get("meetroomid"));
					if (meetRoomId.length() > 0
							&& meetRoomId.equals(ConvertUtil.convertToString(boardroom.get("id")))) {
						List<Map<String, Object>> applyHistory;
						if (boardroom.containsKey("applylist")) {
							applyHistory = (List<Map<String, Object>>) boardroom.get("applylist");
							applyHistory.add(applyEntity);
						} else {
							applyHistory = new ArrayList<Map<String, Object>>();
							applyHistory.add(applyEntity);
							boardroom.put("applylist", applyHistory);
						}
					}
				}
				result.add(boardroom);
			}
		}
		// 兼容Android端接口，返回数据增加外层Map
		Map<String, Object> dataMap = new HashMap<>();
		dataMap.put("dataList", result);
		return ResponseResult.ok(dataMap);
	}

	/**
	 * @author zhanglongfei
	 * @date 2019年10月25日
	 * @description 会议室电子牌信息，特殊接口，给会议室电子牌使用，不需要登录
	 * @return
	 */
	@GetMapping(value = "/elecCard")
	public ResponseResult<Object> elecCard(@RequestParam Map<String, Object> paraMap) {
		Map<String, Object> result = new HashMap<String, Object>();
		Map<String, Object> model = service.queryMapById(paraMap.get("id").toString());
		result.put("model", model);// 会议室信息
		List<Map<String, Object>> applyList = meetRoomApplyService.queryMapByWhere("enabled=1 and endtime>"
				+ SQLAdapter.getDate() + " and state=9 and meetroomid ='" + model.get("id") + "' order by begintime");
		Map<String, Object> current = null;
		List<Map<String, Object>> waitList = new ArrayList<Map<String, Object>>();
		Date now = new Date();
		for (Map<String, Object> applyEntity : applyList) {
			Date beginTime = DateUtil.stringToDate(applyEntity.get("begintime").toString());
			Date endTime = DateUtil.stringToDate(applyEntity.get("endtime").toString());
			if (beginTime.compareTo(now) < 1 && endTime.compareTo(now) > -1) {
				current = applyEntity;
			} else {
				if (waitList.size() >= 2) {
					break;
				}
				waitList.add(applyEntity);
			}
		}
		String version = "V1.1";
		result.put("current", current);// 当前会议
		result.put("waitList", waitList);// 即将召开
		if (!paraMap.containsKey("version") || !version.equals(ConvertUtil.convertToString(paraMap.get("version")))) {
			result.put("command", "refresh");
		} else {
			result.put("command", "no"); // 和电子屏界面约定的命令参数，no忽略，refresh刷新页面
		}
		result.put("version", version);
		return ResponseResult.ok(result);
	}

	/**
	 * @description: 判断当前用户是否能够上传会议室图片
	 * @author: chengengwei
	 * @date: 2021-5-31
	 * @modify:
	 */
	@Override
	protected void afterLoad(Map<String, Object> paraMap) {
		List<CboRoleEntity> cboRoleEntityList = this.getUserBean().getRoleList();
		paraMap.put("editable", cboRoleEntityList.stream()
				.anyMatch(item -> MeetSystemConst.UploadRoomPicture.equals(item.getCode())));
	}
}
